<?php
//订单支付方式
function payment_list($type = 'order', $virtual = false) {
	global $pe;
	$cache_payment = cache::get('payment');
	$payment_list = array();
	if ($type == 'order_add') {
		foreach ($cache_payment as $k=>$v) {
			if (!$v['payment_state']) continue;
			if ($v['payment_type'] == 'adminpay') continue;
			if ($virtual && $v['payment_type'] == 'cod') continue;
			if ($v['payment_type'] != 'cod') {
				if ($online) continue;
				$v['payment_name'] = '在线支付';
				$online = true;
			}
			$payment_list[$k]['payment_name'] = $v['payment_name'];		
			$payment_list[$k]['payment_type'] = $v['payment_type'];
		}
	}
	else {
		foreach ($cache_payment as $k=>$v) {
			if (!$v['payment_state']) continue;
			if ($v['payment_type'] == 'adminpay') continue;
			if ($v['payment_type'] == 'cod') continue;
			if ($pe['client'] == 'h5' && in_array($v['payment_type'], array('bank'))) continue;
			if ($pe['client'] == 'h5_wx' && in_array($v['payment_type'], array('alipay', 'bank'))) continue;
			if ($pe['client'] == 'minapp' && in_array($v['payment_type'], array('alipay', 'bank'))) continue;
			if ($v['payment_type'] == 'balance' && !pe_login('user')) continue;
			if ($type == 'recharge' && in_array($v['payment_type'], array('cod', 'balance', 'bank'))) continue;
			$payment_list[$k]['payment_name'] = $v['payment_name'];		
			$payment_list[$k]['payment_logo'] = $v['payment_logo'];	
			$payment_list[$k]['payment_type'] = $v['payment_type'];
		}
	}
	return $payment_list;
}

//订单状态计算
function order_stateshow($state, $type = '') {
	global $ini;
	$ini['order_state']['wcheck'] = '待审核';
	$ini['order_state']['wtuan'] = '待成团';
	$value = $ini['order_state'][$state] ? $ini['order_state'][$state] : '';
	if ($state == 'success') {
		$color = "cgreen";
	}
	elseif ($state == 'close') {
		$color = "cbbb";
	}
	else {
		$color = "corg";
	}
	if ($type == 'html') return "<span class=\"{$color}\">{$value}</span>";
	if ($type == 'arr') return array('style'=>$color, 'val'=>$value);
	return $value;
}

//订单商品规格显示
function order_skushow($product_rule) {
	$product_rule = unserialize($product_rule) === false ? $product_rule : unserialize($product_rule);
	if (is_array($product_rule)) {
		foreach ($product_rule as $v) {
			//$arr[] = "{$v['name']}：{$v['value']}";
			$arr[] = $v['value'];
		}	
		return implode(';', $arr);
	}
	else {
		return $product_rule;	
	}
}

//计算订单运费
function order_wlmoney($product_list = array(), $address = '') {
	global $db;
	$tongji_list = array();
	$sz_wlmoney = $xz_wlmoney = 0;
	foreach ($product_list as $v) {
		if ($v['wlmb_id']) {
			$tongji_list[$v['wlmb_id']] += $v['product_num'];
		}
	}
	foreach ($tongji_list as $wlmb_id=>$num) {
		$wlmb = $db->pe_select('wlmb', array('wlmb_id'=>$wlmb_id));	
		$wlmb_data = $wlmb['wlmb_data'] ? json_decode($wlmb['wlmb_data'], true) : array();
		foreach ($wlmb_data as $v) {
			$city_arr = $v['city'] ? explode(',', $v['city']) : array();
			if (in_array($address, $city_arr)) {
				$sz_wlmoney = $v['money'] >= $sz_wlmoney ? $v['money'] : $sz_wlmoney;
				if ($num > $v['value'] && $v['value2'] > 0) {
					$xz_wlmoney += ceil(($num - $v['value'])/$v['value2']) * $v['money2'];
				}
			}
		}
	}
	return pe_num($sz_wlmoney + $xz_wlmoney, 'round', 2);
}

//订单创建操作
function order_add_callback($order, $cart_id = array()) {
	global $db;
	$info = is_array($order) ? $order : $db->pe_select('order', array('order_id'=>pe_dbhold($order)));
	if (!$info['order_id']) return false;
	//扣除交易使用积分和优惠券
	add_pointlog($info['user_id'], 'order_pay', $info['order_point_use'], "支付订单抵现扣除，单号【{$info['order_id']}】");
	user_quanupdate($info['order_quan_id'], 1);
	//更新商品库存
	$orderdata_list = $db->pe_selectall('orderdata', array('order_id'=>$info['order_id']));
	foreach ($orderdata_list as $v) {
		product_jsnum($v['product_guid'], 'del_num', $v['product_num']);
	}
	//更新用户订单数
	$user_ordernum = $db->pe_num('order', array('user_id'=>$info['user_id']));
	$db->pe_update('user', array('user_id'=>$info['user_id']), array('user_ordernum'=>$user_ordernum));
	//发送消息通知
	add_noticelog($info['user_id'], 'order_add', $info);
	//清空购物车
	$db->pe_delete('cart', array('cart_id'=>pe_dbhold($cart_id)));
	return true;
}

//订单付款操作
function order_pay_callback($order, $pay) {
	global $db;
	$cache_payment = cache::get('payment');
	$info = is_array($order) ? $order : $db->pe_select('order', array('order_id'=>pe_dbhold($order)));
	if (!$info['order_id']) return false;
	if ($info['order_state'] != 'wpay') return false;
	$sql_set['order_payid'] = $pay['pay_id'];
	$sql_set['order_outid'] = $pay['order_outid'];
	$sql_set['order_payment'] = $pay['order_payment'];
	$sql_set['order_payment_name'] = $pay['order_payment_name'];
	$sql_set['order_ptime'] = $pay['order_ptime'];
	$sql_set['order_pstate'] = $pay['order_pstate'];
	//检测是否为拼团
	if ($info['order_type'] == 'pintuan') {
		$sql_set['order_state'] = 'wtuan';
	}
	else {
		$sql_set['order_state'] = 'wsend';
	}
    if ($db->pe_update('order', array('order_id'=>$info['order_id']), pe_dbhold($sql_set))) {
 	    $user = $db->pe_select('user', array('user_id'=>$info['user_id']));
        //更新商品销量
        $orderdata_list = $db->pe_selectall('orderdata', array('order_id'=>$info['order_id']));
        foreach ($orderdata_list as $v) {
            product_jsnum($v['product_id'], 'add_sellnum', $v['product_num']);
			add_buylog($user, $v['product_guid'], $v['product_num']);
        }
        //拼团订单检测成团
        if ($info['order_type'] == 'pintuan') {
            pintuan_callback($info);
        }
        //虚拟商品自动发货
        if ($info['order_virtual']) {
            virtual_order_send_callback($info);
        }
        //发送消息通知
        $notice = array_merge($info, $sql_set);
        add_noticelog($info['user_id'], 'order_pay', $notice);
        return true;
    }
    return false;
}

//订单发货操作
function order_send_callback($order, $order_wl_id='', $order_wl_name='') {
	global $db;
	$info = is_array($order) ? $order : $db->pe_select('order', array('order_id'=>pe_dbhold($order)));
	if (!$info['order_id']) return false;
	$sql_set['order_wl_id'] = $order_wl_id;
	$sql_set['order_wl_name'] = $order_wl_name;
	$sql_set['order_state'] = 'wget';
	$sql_set['order_sstate'] = 1;
	$sql_set['order_stime'] = time();
	if ($db->pe_update('order', array('order_id'=>$info['order_id']), pe_dbhold($sql_set))) {
		//取消退款中子订单
		pe_lead('hook/refund.hook.php');
		refund_close($info['order_id'], 'all');
		//发送消息通知
		$notice = array_merge($info, $sql_set);
		add_noticelog($info['user_id'], 'order_send', $notice);
		return true;
	}
	else {
		return false;
	}
}

//虚拟订单发货操作
function virtual_order_send_callback($order) {
	global $db;
	$info = is_array($order) ? $order : $db->pe_select('order', array('order_id'=>pe_dbhold($order)));
	if (!$info['order_id']) return false;
	if (!$info['order_virtual']) return true;
	$orderdata = $db->pe_select('orderdata', array('order_id'=>$info['order_id']));
	$info['product_id'] = $orderdata['product_id'];
	$info['product_num'] = $orderdata['product_num'];
	//更新已过期卡密
	prokey_check($info['product_id']);
	//给用户发放卡密
	$prokey_list = $db->pe_selectall('prokey', array('product_id'=>$info['product_id'], 'prokey_state'=>'new', 'order by'=>'prokey_id asc'), '*', array($info['product_num']));
	if (count($prokey_list) >= $info['product_num']) {
		foreach ($prokey_list as $v) {
			$sql_set['prokey_state'] = 'success';
			$sql_set['order_id'] = $info['order_id'];
			$sql_set['user_id'] = $info['user_id'];
			$sql_set['user_name'] = $info['user_name'];
			$result = $db->pe_update('prokey', array('prokey_id'=>$v['prokey_id']), pe_dbhold($sql_set));
		}
	}
	if ($result) {
		order_send_callback($info);
		order_success_callback($info);
		return true;
	}
	else {
		return false;
	}
}

//订单交易完成操作
function order_success_callback($order) {
	global $db, $cache_setting, $ini;
	$info = is_array($order) ? $order : $db->pe_select('order', array('order_id'=>pe_dbhold($order)));
	if (!$info['order_id']) return false;
	$sql_set['order_state'] = 'success';
	if ($info['order_payment'] == 'cod') {
		$sql_set['order_pstate'] = 1;
		$sql_set['order_ptime'] = time();
	}
	$sql_set['order_ftime'] = time();
	if ($db->pe_update('order', array('order_id'=>$info['order_id']), pe_dbhold($sql_set))) {
		//取消退款处理中子订单
		pe_lead('hook/refund.hook.php');
		refund_close($info['order_id'], 'all');
		//货到付款更新销量
		if ($info['order_payment'] == 'cod') {
			$orderdata_list = $db->pe_selectall('orderdata', array('order_id'=>$info['order_id']));
			foreach ($orderdata_list as $v) {
				product_jsnum($v['product_id'], 'add_sellnum', $v['product_num']);
			}
		}
		//更新用户累计消费
		$db->pe_update('user', array('user_id'=>$info['user_id']), "`user_money_cost` = `user_money_cost` + '{$info['order_money']}'");
		userinfo_callback($info['user_id']);
        //发放积分奖励
        add_pointlog($info['user_id'], 'add', $info['order_point_get'], "交易完成获得，单号【{$info['order_id']}】");
		//给上级推广用户发钱
		if ($cache_setting['tg_state']) {
			$tguser_list = tguser_list($info['user_id'], 3);
			foreach ($tguser_list as $k=>$v) {
				$moneylog_money = $info['order_money'] * $cache_setting["tg_fc{$k}"];
				$moneylog_text = "获得{$ini['tg_level'][$k]}级粉丝【{$info['user_name']}】".($cache_setting["tg_fc{$k}"]*100)."%收益，单号【{$info['order_id']}】消费{$info['order_money']}元";
				add_moneylog($v['user_id'], 'tg', $moneylog_money, $moneylog_text);
				//计算已获得总佣金
				//$tj = $db->pe_select('moneylog', array('user_id'=>$v['user_id'], 'moneylog_type'=>'tg'), 'sum(moneylog_in) as `money`');
				//$db->pe_update('user', array('user_id'=>$v['user_id']), array('user_money_tg'=>$tj['money']));
			}
		}
		return true;
	}
	else {
		return false;
	}
}

//订单关闭操作($refund是否还处理退款逻辑)
function order_close_callback($order, $order_closetext = '', $refund = true) {
	global $db;
	pe_lead('hook/refund.hook.php');
	$info = is_array($order) ? $order : $db->pe_select('order', array('order_id'=>pe_dbhold($order)));
	if (!$info['order_id']) return false;
	if ($info['order_state'] == 'close') return true;
	$sql_set['order_ftime'] = time();
	$sql_set['order_state'] = 'close';
	$sql_set['order_closetext'] = $order_closetext;
	if ($db->pe_update('order', array('order_id'=>$info['order_id']), pe_dbhold($sql_set))) {
		$info_list = $db->pe_selectall('orderdata', array('order_id'=>$info['order_id']));
		if ($info['order_pstate'] && $refund) {
			//已付款生成退款单退款
			foreach ($info_list as $v) {
				refund_success(add_refund($v, '订单关闭退款'));
			}
		}
		//未付款可以释放商品库存
		if (!$info['order_pstate']) {
			foreach ($info_list as $v) {
				product_jsnum($v['product_guid'], 'add_num', $v['product_num']);
			}
		}
		//退积分和优惠券
		add_pointlog($info['user_id'], 'back', $info['order_point_use'], "订单关闭退回，单号【{$info['order_id']}】");
		user_quanupdate($info['order_quan_id'], 0);
		//发送消息通知
		$notice = array_merge($info, $sql_set);
		add_noticelog($info['user_id'], 'order_close', $notice);
		return true;
	}
	else {
		return false;
	}
}

//订单评价操作
function order_comment_callback($order) {
	global $db, $cache_setting;
	$info = is_array($order) ? $order : $db->pe_select('order', array('order_id'=>pe_dbhold($order)));
	if (!$info['order_id']) return false;
	if ($db->pe_update('order', array('order_id'=>$info['order_id']), array('order_comment'=>1))) {
		//更新商品评价数
		$info_list = $db->pe_selectall('orderdata', array('order_id'=>$info['order_id']));
		foreach ($info_list as $k=>$v) {
			product_jsnum($v['product_id'], 'commentnum');
			add_pointlog($info['user_id'], 'add', $cache_setting['point_comment'], "发表评价获得，单号【{$info['order_id']}】，商品【{$v['product_name']}】");
		}
		return true;
	}
	else {
		return false;
	}
}

//订单调价显示
function order_jjmoney_show($money) {
	if ($money > 0) {
		return '手动改价 +'.round($money, 2).'元';
	}
	elseif ($money < 0) {
		return '手动改价 '.round($money, 2).'元';
	}
	return '-';
}

//开+参团检测
function pintuan_check($huodong_id, $pintuan_id = 0) {
	global $db, $user;
	$info = $db->pe_select('huodong', array('huodong_id'=>$huodong_id));
	if (!$info['huodong_id']) return array('code'=>0, 'msg'=>'活动已结束');
	if ($info['huodong_stime'] > time() or $info['huodong_etime'] <= time()) return array('code'=>0, 'msg'=>'拼团已结束');
	if ($pintuan_id) {
		$info = $db->pe_select('pintuan', array('pintuan_id'=>$pintuan_id));
		if (!$info['pintuan_id']) return array('code'=>0, 'msg'=>'拼团无效');
		if (in_array($info['pintuan_state'], array('success', 'close'))) return array('code'=>0, 'msg'=>'拼团已结束');
	}
	if ($db->pe_num('pintuanlog', array('pintuan_id'=>$pintuan_id, 'user_id'=>$user['user_id']))) return array('code'=>0, 'msg'=>'不可参团');
	return array('code'=>1);
}

//开+参团付款回调
function pintuan_callback($info) {
	global $db;
	$info = is_array($info) ? $info : $db->pe_select('order', array('order_id'=>pe_dbhold($info)));
	if (!$info['order_id']) return false;
	//如果拼团活动或团单结束则订单退款关闭
	/*if (!pintuan_check($info['huodong_id'], $info['pintuan_id'])) {
		order_close_callback($order, '拼团结束，订单自动关闭退款');
		return true;
	}*/
	//如果是团长付款
	if (!$info['pintuan_id']) {
		$huodong = $db->pe_select('huodongdata', array('huodong_id'=>$info['huodong_id']));
		$sql_set['pintuan_id'] = $info['pintuan_id'] = $info['order_id'];
		$sql_set['pintuan_num'] = $huodong['product_ptnum'];
		$sql_set['pintuan_joinnum'] = 1;
		$sql_set['pintuan_atime'] = time();
		$sql_set['pintuan_stime'] = time();				
		$sql_set['pintuan_etime'] = time() + 86400;
		//如果拼团结束时间超过活动结束时间，以活动结束时间为准
		if ($sql_set['pintuan_etime'] > $huodong['huodong_etime']) $sql_set['pintuan_etime'] = $huodong['huodong_etime'];
		$sql_set['pintuan_state'] = 'wtuan';
		$sql_set['product_id'] = $huodong['product_id'];		
		$sql_set['product_name'] = $huodong['product_name'];
		$sql_set['product_logo'] = $huodong['product_logo'];	
		$sql_set['product_money'] = $huodong['product_money'];
		$sql_set['huodong_id'] = $huodong['huodong_id'];
		$user = $db->pe_select('user', array('user_id'=>$info['user_id']), 'user_id, user_name, user_logo');
		$sql_set['user_id'] = $user['user_id'];	
		$sql_set['user_name'] = $user['user_name'];
		$sql_set['user_logo'] = $user['user_logo'];	
		$db->pe_insert('pintuan', pe_dbhold($sql_set));
		$db->pe_update('order', array('order_id'=>$info['order_id']), array('pintuan_id'=>$info['pintuan_id']));
	}
	//插入参团记录
	$sqlset_pintuanlog['pintuanlog_atime'] = time();
	$sqlset_pintuanlog['pintuan_id'] = $info['pintuan_id'];
	$sqlset_pintuanlog['order_id'] = $info['order_id'];
	if (!is_array($user)) $user = $db->pe_select('user', array('user_id'=>$info['user_id']), 'user_id, user_name, user_logo');
	$sqlset_pintuanlog['user_id'] = $user['user_id'];
	$sqlset_pintuanlog['user_name'] = $user['user_name'];
	$sqlset_pintuanlog['user_logo'] = $user['user_logo'];
	$db->pe_insert('pintuanlog', pe_dbhold($sqlset_pintuanlog));
	//计算成团需人数
	$pintuan = $db->pe_select('pintuan', array('pintuan_id'=>$info['pintuan_id']));
	//计算已参与人数
	$sqlset_pintuan['pintuan_joinnum'] = $db->pe_num('pintuanlog', array('pintuan_id'=>$info['pintuan_id']));
	//如果拼团达到人数
	if ($sqlset_pintuan['pintuan_joinnum'] >= $pintuan['pintuan_num']) {
		$sqlset_pintuan['pintuan_state'] = 'success';	
		//检测虚拟商品自动发货
		$order_list = $db->pe_selectall('order', array('pintuan_id'=>$info['pintuan_id'], 'order_state'=>'wtuan'));
		foreach ($order_list as $v) {
			virtual_order_send_callback($v);
		}
		//待成团订单变待发货
		$db->pe_update('order', array('pintuan_id'=>$info['pintuan_id'], 'order_state'=>'wtuan'), array('order_state'=>'wsend'));
		//未付款订单关闭
		$order_list = $db->pe_selectall('order', array('pintuan_id'=>$info['pintuan_id'], 'order_state'=>'wpay'));
		foreach ($order_list as $v) {
			order_close_callback($v, "拼团结束，未付款订单自动关闭");
		}
	}
	//更新团单信息
	$sqlset_pintuan['pintuan_id'] = $info['pintuan_id'];
	$db->pe_update('pintuan', array('pintuan_id'=>$info['pintuan_id']), pe_dbhold($sqlset_pintuan));
}

//获取快递轨迹信息
/**
 * @param $kuaidi_id
 * @param $kuaidi_code
 * @return array
 */
function order_kuaidi($kuaidi_id, $kuaidi_code = '') {
	global $db, $cache_setting;
	$info = $db->pe_select('kuaidilog', array('kuaidi_id'=>$kuaidi_id));
	if ($info['kuaidilog_state'] == 1 or time() - $info['kuaidilog_utime'] <= 300) {
		$kuaidilog_list = unserialize($info['kuaidilog_list']);
	}
	else {
		if (stripos($kuaidi_code, '百事') !== false or stripos($kuaidi_code, '汇通') !== false) $code = 'HTKY';
		if ($code) {
		    $url = "https://wuliu.market.alicloudapi.com/kdi?no={$kuaidi_id}&type={$code}";//api访问链接		
		}
		else {
	    	$url = "https://wuliu.market.alicloudapi.com/kdi?no={$kuaidi_id}";//api访问链接	
		}
	    $headers = array();
	    array_push($headers, "Authorization:APPCODE {$cache_setting['web_wlkey']}");
	    $curl = curl_init($url);
	    curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'GET');
	    curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
	    curl_setopt($curl, CURLOPT_FAILONERROR, false);
	    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
	    curl_setopt($curl, CURLOPT_HEADER, false);
	    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
	    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
		$json = json_decode(curl_exec($curl), true);
		curl_close($curl);
		if ($json['status'] == 0) {
		    if (is_array($json['result']['list'])) {
                foreach ($json['result']['list'] as $k=>$v) {
                    $kuaidilog_list[$k] = array('time'=>$v['time'], 'text'=>$v['status']);
                }
		    }
			if (!is_array($kuaidilog_list)) $kuaidilog_list = array(array('time'=>pe_date(time()), 'text'=>'暂无物流信息'));
			$sql_set['kuaidilog_list'] = serialize($kuaidilog_list);
			$sql_set['kuaidilog_utime'] = time();
			$sql_set['kuaidilog_state'] = $json['result']['issign'] ? 1 : 0;		
			if ($info['kuaidilog_id']) {
				$db->pe_update('kuaidilog', array('kuaidilog_id'=>$info['kuaidilog_id']), pe_dbhold($sql_set, array('kuaidilog_list')));
			}
			else {
				$sql_set['kuaidi_id'] = $kuaidi_id;
				//$sql_set['kuaidi_name'] = $json['result']['expName'];
				$sql_set['kuaidi_code'] = $json['result']['type'];
				$db->pe_insert('kuaidilog', pe_dbhold($sql_set, array('kuaidilog_list')));
			}
		}
		else {
			$kuaidilog_list = array(array('time'=>pe_date(time()), 'text'=>$json['msg']));
		}	
	}	
	//按日期倒序显示
	foreach ($kuaidilog_list as $v) {
		$new_list[$v['time']] = $v;
	}
	krsort($new_list);
	return array_values($new_list);
}

//生成订单券码
function order_code() {
	global $db;
	for ($i=1; $i<=12; $i++) {
		$order_code .= mt_rand(0, 9);
	}
	$num = $db->pe_num('order', array('order_code'=>$order_code));
	if ($num) {
		return order_code();
	}
	else {
		return $order_code;
	}
}

//订单券码显示
function order_codeshow($code) {
	return implode(' ', str_split($code, 4));
}
?>